iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0
佛心分享-IT 人自學之術

演算法與資料結構入門:30天基礎學習之旅系列 第 8

Coding Practice:Get The Intersection Of Two Arrays-day8

  • 分享至 

  • xImage
  •  

Get The Intersection Of Two Arrays

Here's a quick exercise: If there are two unsorted arrays, write a function that returns their intersection.

做個動腦練習,假設有兩個 unsorted arrays,寫一個 function 回傳兩 array 交集的值
先不要偷看答案唷~

提示:使用linear search


Answer:

const arrayA = [1,6,3,9,17,22,18,7,5,2,21,12,37,33,8,109,77,23,14,11];
const arrayB = [2,5,8,12,75,17,23,14,36,33,7,17,9,77,56,62,1,102,3];

finction getIntersection(arrA,arrB){
    const result=[];
    for(let i =0; i<arrA.length;i++){
        for(let j=0;j<arrB.length;j++){
            if(arrA[i]===arrB[j]){
                result.push(arrA[i]);
            }
        }
    }
    return result;
}

getIntersection(arrayA ,arrayB ); // [1, 3, 9, 17, 17, 7, 5, 2, 12, 33, 8, 77, 23, 14]

Here's a quick exercise: If there are two sorted arrays, write a function that returns their intersection.

做個動腦練習,假設有兩個 sorted arrays,寫一個 function 回傳兩 array 交集的值
先不要偷看答案唷~

提示:使用binary search


Answer:

 const arrayA = [1, 2, 3, 5, 6, 7, 8, 9, 11, 12, 14, 17, 18, 21, 22, 23, 33, 37, 77, 109];
 const arrayB = [1, 2, 3, 5, 7, 8, 9, 12, 14, 17, 23, 33, 36, 56, 62, 75, 77, 102];

function binartSearch(arr, target) {
    let min = 0,
        max = arr.length - 1;
        while (min <= max) {
            let mid = Math.floor((min + max) / 2);
            if (arr[mid] === target) {
                return true;
            } else if (arr[mid] < target) {
                min = mid + 1;
            } else {
                max = mid - 1;
            }
        }
    return false;
}

function getIntersectionBinary(arrA, arrB) {
    let intersection = [];
    for (let i = 0; i < arrA.length; i++) {
        if (binartSearch(arrB, arrA[i])) {
            intersection.push(arrA[i]);
         }
    }
    return intersection;
}

console.log(getIntersectionBinary(arrayA, arrayB)); // [1, 2, 3, 5, 7, 8, 9, 12, 14, 17, 23, 33, 77]

上一篇
Introduction to Binary Search-day7
下一篇
Concept of counter-day9
系列文
演算法與資料結構入門:30天基礎學習之旅13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言